﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class HalfUniformCrossover : CrossoverOperator
    {
        public HalfUniformCrossover(bool[] parent1, bool[] parent2)
        {
            this.parent1 = parent1;
            this.parent2 = parent2;
        }

        public HalfUniformCrossover()
        {

        }

        public override Pair<bool[], bool[]> doCrossover()
        {
            bool[] child1 = new bool[parent1.Length];
            bool[] child2 = new bool[parent1.Length];
            int[] differences = new int[parent1.Length];

            int j = -1;
           
            for (int i = 0; i < parent1.Length; i++)
            {
                if ((parent1[i] && !parent2[i]) || (!parent1[i] && parent2[i]))
                {
                    differences[++j] = i;
                }
                else
                {
                    child1[i] = parent1[i];
                    child2[i] = parent2[i];
                }
            }
            

            Random generator = new Random();

            int swaps = 0;
            int swapped_pos = 0;
            while (swaps < (j + 1) / 2)
            {
                swapped_pos = generator.Next(j+1);

                if (differences[swapped_pos] != -1)
                {
                    swaps++;
                    child2[differences[swapped_pos]] = parent1[differences[swapped_pos]];
                    child1[differences[swapped_pos]] = !child2[differences[swapped_pos]];
                    differences[swapped_pos] = -1;
                }

            }

            return new Pair<bool[], bool[]>(child1, child2);
        }
    }
}
